package com.elitel.frame.business.service.common.processor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.elitel.common.utils.RedisUtils;
import com.elitel.common.utils.StringUtils;
import com.elitel.frame.business.service.common.CommonServerProcessor;
import com.elitel.frame.core.util.NashornUtil;
import com.elitel.frame.main.entity.SysPrjservice;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

import static com.elitel.common.constant.RedisKeyConstant.SERVER_INFO_KEY;
import static com.elitel.common.core.constant.RequestConstant.GUID;

@Slf4j
public class ResponseConversionProcessor implements CommonServerProcessor {


    /**
     * 请求之后的拦截
     *
     * @param map
     * @param result
     * @param request
     * @param response
     */
    public Object post(Map map, Object result, HttpServletRequest request, HttpServletResponse response) {

        String guid = (String) map.get(GUID);
        // 获取缓存中的服务
        Object serverInfo = RedisUtils.hGet(SERVER_INFO_KEY, guid);
        log.info("服务id为：{}，获取缓存中的服务信息为：{}", guid, serverInfo);
        if (serverInfo != null) {

            SysPrjservice sysPrjservice = JSONObject.parseObject(serverInfo + "", SysPrjservice.class);

            String resCvsJs = sysPrjservice.getResCvsJs();
            if (StringUtils.isNotEmpty(resCvsJs)){
                Object o = NashornUtil.executeJsTransformation(result, resCvsJs);
                // 重置 result 对象为 o 的新实例
                log.info("请求之后的拦截转换后的结果：{}", o);

                return o;
            }

        }
        return result;
    }


}
